/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.document.service.file.impl;

import com.google.common.base.Strings;
import com.je.common.base.DynaBean;
import com.je.common.base.service.MetaService;
import com.je.document.entity.DocumentMetadataDO;
import com.je.document.reflection.BeanMappingHelper;
import com.je.document.service.file.FileMetaDataService;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;

@Service
public class FileMetaDataServiceImpl implements FileMetaDataService {

    @Autowired
    private MetaService metaService;

    @Override
    public DocumentMetadataDO selectMetadata(String relId, String code) {
        List<Map<String, Object>> metaBeanList = metaService.selectSql(ConditionsWrapper.builder().table("JE_DOCUMENT_METADATA")
                .eq("is_deleted", 0)
                .eq("rel_id", relId)
                .eq("code", code));
        if (metaBeanList == null) {
            return null;
        }
        return BeanMappingHelper.transform(metaBeanList.get(0), DocumentMetadataDO.class);
    }

    @Override
    public DynaBean selectMetadataBean(String relId, String code) {
        List<DynaBean> beans = metaService.select("JE_DOCUMENT_METADATA",ConditionsWrapper.builder()
                .eq("is_deleted", 0)
                .eq("rel_id", relId)
                .eq("code", code));
        return beans == null || beans.isEmpty()? null:beans.get(0);
    }

    @Override
    public List<DocumentMetadataDO> selectFileMetadata(String fileKey) {
        List<Map<String, Object>> metaBeanList = metaService.selectSql("select t.* from je_document_metadata t INNER JOIN je_document_rel m on m.je_document_rel_id = t.rel_id and m.is_deleted = 0 where t.is_deleted=0 and m.file_key = {0}", fileKey);
        if (metaBeanList == null) {
            return null;
        }
        return BeanMappingHelper.transformList(metaBeanList, DocumentMetadataDO.class);
    }

    @Override
    public List<DocumentMetadataDO> selectFileMetadataById(List<Long> relIds) {
        List<Map<String, Object>> metaBeanList = metaService.selectSql(ConditionsWrapper.builder().table("JE_DOCUMENT_METADATA").eq("is_deleted", 0).in("rel_id", relIds));
        if (metaBeanList == null) {
            return null;
        }
        return BeanMappingHelper.transformList(metaBeanList, DocumentMetadataDO.class);
    }

    @Override
    public void updateTempToForm(List<String> relIds, String modifiedUserId) {
        metaService.executeSql("update je_document_metadata set content = 'FORM', modified_time = NOW(),modified_user={0} where code = 'uploadType' AND content = 'TEMP' AND is_deleted = 0 AND rel_id in ({1})", modifiedUserId, relIds);
    }

    @Override
    public void copyFileRelMetadata(String userId, String oldRelId, String newRelId, String newPkValue, String newFuncCode, String newTableCode, String newFieldCode) {
        List<DynaBean> metaBeans = metaService.select("JE_DOCUMENT_METADATA", ConditionsWrapper.builder()
                .eq("rel_id", oldRelId)
                .eq("is_deleted", 0));
        DynaBean eachNewBean;
        for (DynaBean eachBean : metaBeans) {
            eachNewBean = new DynaBean("JE_DOCUMENT_METADATA", false);
            eachNewBean.set("file_id", eachBean.getStr("file_id"));
            eachNewBean.set("rel_id", newRelId);
            if (!Strings.isNullOrEmpty(newFuncCode)) {
                eachNewBean.set("code", newFuncCode);
            } else if (!Strings.isNullOrEmpty(newTableCode)) {
                eachNewBean.set("code", newTableCode);
            } else if (!Strings.isNullOrEmpty(newPkValue)) {
                eachNewBean.set("code", newPkValue);
            } else if (!Strings.isNullOrEmpty(newFieldCode)) {
                eachNewBean.set("code", newFieldCode);
            }
            eachNewBean.set("content", eachBean.getStr("content"));
            eachNewBean.set("create_user", eachBean.getStr("create_user"));
            eachNewBean.set("modified_user", eachBean.getStr("modified_user"));
            metaService.insert(eachNewBean);
        }
    }

}
